package org.his.utils;

import net.sourceforge.pinyin4j.PinyinHelper;
import net.sourceforge.pinyin4j.format.HanyuPinyinCaseType;
import net.sourceforge.pinyin4j.format.HanyuPinyinOutputFormat;
import net.sourceforge.pinyin4j.format.HanyuPinyinToneType;
import net.sourceforge.pinyin4j.format.HanyuPinyinVCharType;
import net.sourceforge.pinyin4j.format.exception.BadHanyuPinyinOutputFormatCombination;

public class PinYin4jUtil {

    public static String getPingYin(String src) {
        char[] inputChar = null;
        inputChar = src.toCharArray();
        int inputCharLength = inputChar.length;
        String[] piword = new String[inputCharLength];
        HanyuPinyinOutputFormat hPinyinOutputFormat = new HanyuPinyinOutputFormat();
        //大小写
        hPinyinOutputFormat.setCaseType(HanyuPinyinCaseType.LOWERCASE);
        //带拼音状态(toneType和charType必须成对使用，否则会异常)
//        hPinyinOutputFormat.setToneType(HanyuPinyinToneType.WITH_TONE_MARK);
//        hPinyinOutputFormat.setVCharType(HanyuPinyinVCharType.WITH_U_UNICODE);
        hPinyinOutputFormat.setToneType(HanyuPinyinToneType.WITHOUT_TONE);
        hPinyinOutputFormat.setVCharType(HanyuPinyinVCharType.WITH_V);
        String piStr = "";
        try {
            for (int i = 0; i < inputCharLength; i++) {
                // 判断是否为汉字字符
                if (java.lang.Character.toString(inputChar[i]).matches("[\\u4E00-\\u9FA5]+")) {
                    piword = PinyinHelper.toHanyuPinyinStringArray(inputChar[i], hPinyinOutputFormat);
                    piStr += piword[0];
                } else
                    piStr += java.lang.Character.toString(inputChar[i]);
            }
            // System.out.println(t4);
            return piStr;
        } catch (BadHanyuPinyinOutputFormatCombination e1) {
            e1.printStackTrace();
        }
        return piStr;
    }

    // 返回中文的首字母
    public static String getPinYinHeadChar(String str) {

        String convert = "";
        for (int j = 0; j < str.length(); j++) {
            char word = str.charAt(j);
            String[] pinyinArray = PinyinHelper.toHanyuPinyinStringArray(word);
            if (pinyinArray != null) {
                convert += pinyinArray[0].charAt(0);
            } else {
                convert += word;
            }
        }
        return convert;
    }
}
